import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Modal,
  Form,
  Select,
  Tag,
  Popconfirm,
  Toast,
  Typography,
  Row,
  Col,
} from '@douyinfe/semi-ui';
import {
  IconPlus,
  IconEdit,
  IconDelete,
  IconUserGroup,
  IconKey,
  IconMenu,
  IconSearch,
  IconRefresh
} from '@douyinfe/semi-icons';
import { userApi, SysUser, AssignRolesRequest } from '../../api/user';
import { roleApi, SysRole } from '../../api/role';
import { PageQuery } from '../../api/request';
import UserRoleAssignment from '../../components/UserRoleAssignment';
import PermissionAssignment from '../../components/PermissionAssignment';
import MenuPermissionAssignment from '../../components/MenuPermissionAssignment';

const { Title } = Typography;

// 类型定义
interface UserFormValues {
  username: string;
  password?: string;
  realName: string;
  mobile: string;
  email: string;
  status: number;
}

interface RoleFormValues {
  roleIds: number[];
}

// 验证规则常量
const VALIDATION_RULES = {
  username: [
    { required: true, message: '请输入用户名' },
    { min: 3, message: '用户名至少3个字符' },
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, message: '密码至少6个字符' },
  ],
  realName: [
    { required: true, message: '请输入姓名' },
  ],
  mobile: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '请输入正确的邮箱格式' },
  ],
  status: [
    { required: true, message: '请选择状态' },
  ],
  roleIds: [
    { required: true, message: '请至少选择一个角色' },
    { type: 'array', min: 1, message: '请至少选择一个角色' },
  ],
} as const;

// 统一错误处理函数
const handleApiError = (error: any, defaultMessage: string) => {
  console.error('API错误详情:', error);
  console.error('错误响应:', error?.response);
  console.error('错误数据:', error?.response?.data);
  
  const message = error?.response?.data?.message || error?.message || defaultMessage;
  Toast.error(message);
  
  // 如果是权限错误，给出更明确的提示
  if (error?.response?.status === 403) {
    Toast.error('权限不足，请联系管理员');
  } else if (error?.response?.status === 401) {
    Toast.error('登录已过期，请重新登录');
  }
};

// 表单级别验证函数
const validateUserForm = (values: UserFormValues) => {
  const errors: any = {};
  
  // 自定义验证逻辑
  if (values.email && values.mobile) {
    // 可以添加更复杂的业务逻辑验证
    // 例如：检查邮箱和手机号是否已被其他用户使用
  }
  
  // 密码强度验证（仅在新增用户时）
  if (values.password && values.password.length > 0) {
    if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(values.password)) {
      // 可以添加更严格的密码策略
    }
  }
  
  return errors;
};

// 角色表单验证函数
const validateRoleForm = (values: RoleFormValues) => {
  const errors: any = {};
  
  if (!values.roleIds || values.roleIds.length === 0) {
    errors.roleIds = '请至少选择一个角色';
  }
  
  return errors;
};

const UserManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [users, setUsers] = useState<SysUser[]>([]);
  const [roles, setRoles] = useState<SysRole[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [keyword, setKeyword] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [roleModalVisible, setRoleModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<'add' | 'edit'>('add');
  const [assigningUserId, setAssigningUserId] = useState<number | null>(null);
  const [roleAssignmentVisible, setRoleAssignmentVisible] = useState(false);
  const [permissionAssignmentVisible, setPermissionAssignmentVisible] = useState(false);
  const [menuPermissionAssignmentVisible, setMenuPermissionAssignmentVisible] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
  const [selectedUserName, setSelectedUserName] = useState<string>('');
  
  // 使用getFormApi获取表单API
  const formApiRef = useRef<any>();
  const roleFormApiRef = useRef<any>();

  useEffect(() => {
    loadUsers();
    loadRoles();
  }, [currentPage, pageSize, keyword]);

  const loadUsers = useCallback(async () => {
    setLoading(true);
    try {
      const params: PageQuery = {
        current: currentPage,
        size: pageSize,
        keyword,
      };
      const response = await userApi.pageUsers(params);
      setUsers(response.records);
      setTotal(response.total);
    } catch (error) {
      handleApiError(error, '加载用户列表失败');
    } finally {
      setLoading(false);
    }
  }, [currentPage, pageSize, keyword]);

  const loadRoles = useCallback(async () => {
    try {
      const roleList = await roleApi.listRoles();
      setRoles(roleList);
    } catch (error) {
      handleApiError(error, '加载角色列表失败');
    }
  }, []);

  const handleSearch = useCallback(() => {
    setCurrentPage(1);
    loadUsers();
  }, [loadUsers]);

  const handleReset = useCallback(() => {
    setKeyword('');
    setCurrentPage(1);
    setTimeout(() => loadUsers(), 0);
  }, [loadUsers]);

  const handleAdd = useCallback(() => {
    setEditingUser(null);
    setModalVisible(true);
    // 延迟重置表单，确保Modal已经打开
    setTimeout(() => {
      formApiRef.current?.reset();
      formApiRef.current?.setValues({ status: 1 });
    }, 100);
  }, []);

  const handleEdit = useCallback((user: SysUser) => {
    setEditingUser(user);
    setModalVisible(true);
    // 延迟设置表单值，确保Modal已经打开
    setTimeout(() => {
      formApiRef.current?.setValues({
        ...user,
        password: '', // 编辑时不显示密码
      });
    }, 100);
  }, []);

  const handleDelete = useCallback(async (id: number) => {
    try {
      await userApi.deleteUser(id);
      Toast.success('删除成功');
      loadUsers();
    } catch (error) {
      handleApiError(error, '删除失败');
    }
  }, [loadUsers]);

  const handleResetPassword = useCallback(async (id: number) => {
    try {
      await userApi.resetPassword(id);
      Toast.success('密码重置成功，新密码为：123456');
    } catch (error) {
      handleApiError(error, '重置密码失败');
    }
  }, []);

  const handleAssignRoles = useCallback((userId: number) => {
    setAssigningUserId(userId);
    roleFormApiRef.current?.reset();
    setRoleModalVisible(true);
  }, []);

  const handleRoleAssignment = useCallback((user: SysUser) => {
    setSelectedUserId(user.id!);
    setSelectedUserName(user.username);
    setRoleAssignmentVisible(true);
  }, []);

  const handlePermissionAssignment = useCallback((user: SysUser) => {
    setSelectedUserId(user.id ?? null);
    setSelectedUserName(user.username);
    setPermissionAssignmentVisible(true);
  }, []);

  const handleMenuPermissionAssignment = useCallback((user: SysUser) => {
    setSelectedUserId(user.id ?? null);
    setSelectedUserName(user.username);
    setMenuPermissionAssignmentVisible(true);
  }, []);

  const handleSubmit = useCallback(async (values: UserFormValues) => {
    try {
      if (editingUser) {
        // 编辑时，如果密码为空则不更新密码
        const updateData = { ...values, id: editingUser.id };
        if (!values.password) {
          delete updateData.password;
        }
        await userApi.updateUser(updateData);
        Toast.success('更新成功');
      } else {
        await userApi.createUser(values);
        Toast.success('创建成功');
      }
      setModalVisible(false);
      formApiRef.current?.reset();
      loadUsers();
    } catch (error) {
      handleApiError(error, '操作失败');
    }
  }, [editingUser, loadUsers]);

  const handleRoleSubmit = useCallback(async (values: RoleFormValues) => {
    if (!assigningUserId) return;
    
    try {
      const data: AssignRolesRequest = {
        userId: assigningUserId,
        roleIds: values.roleIds || [],
      };
      await userApi.assignRoles(data);
      Toast.success('分配角色成功');
      setRoleModalVisible(false);
      roleFormApiRef.current?.reset();
      setAssigningUserId(null);
      loadUsers();
    } catch (error) {
      handleApiError(error, '分配角色失败');
    }
  }, [assigningUserId, loadUsers]);

  const getStatusTag = (status: number) => {
    return status === 1 ? (
      <Tag color="green">启用</Tag>
    ) : (
      <Tag color="red">禁用</Tag>
    );
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
    },
    {
      title: '姓名',
      dataIndex: 'realName',
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      width: 130,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 180,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
      render: (time: string) => time?.substring(0, 19),
    },
    {
      title: '操作',
      width: 280,
      render: (record: SysUser) => (
        <Space>
          <Button
            theme="borderless"
            type="primary"
            size="small"
            icon={<IconEdit />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            theme="borderless"
            type="warning"
            size="small"
            icon={<IconKey />}
            onClick={() => handleResetPassword(record.id!)}
          >
            重置密码
          </Button>
          <Button
            theme="borderless"
            type="secondary"
            size="small"
            icon={<IconUserGroup />}
            onClick={() => handleRoleAssignment(record)}
          >
            分配角色
          </Button>
          <Button
            theme="borderless"
            type="tertiary"
            size="small"
            icon={<IconKey />}
            onClick={() => handlePermissionAssignment(record)}
          >
            分配权限
          </Button>
          <Button
            theme="borderless"
            type="tertiary"
            size="small"
            icon={<IconMenu />}
            onClick={() => handleMenuPermissionAssignment(record)}
          >
            菜单权限
          </Button>
          <Popconfirm
            title="确定删除这个用户吗？"
            onConfirm={() => handleDelete(record.id!)}
          >
            <Button
              theme="borderless"
              type="danger"
              size="small"
              icon={<IconDelete />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="space-y-4">
      <Card>
        <div className="flex justify-between items-center mb-4">
          <Title heading={4}>用户管理</Title>
          <Button
            type="primary"
            icon={<IconPlus />}
            onClick={handleAdd}
          >
            新增用户
          </Button>
        </div>

        <Row gutter={16} className="mb-4">
          <Col span={8}>
            <Input
              placeholder="搜索用户名、姓名、手机号、邮箱"
              value={keyword}
              onChange={setKeyword}
              onEnterPress={handleSearch}
            />
          </Col>
          <Col>
            <Space>
              <Button
                type="primary"
                icon={<IconSearch />}
                onClick={handleSearch}
              >
                搜索
              </Button>
              <Button
                icon={<IconRefresh />}
                onClick={handleReset}
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={users}
          loading={loading}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: true,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size!);
            },
          }}
          rowKey="id"
        />
      </Card>

      {/* 用户表单弹窗 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
        centered
        closable
        closeOnEsc
        maskClosable={false}
        motion
        keepDOM={false}
        size="medium"
        bodyStyle={{ padding: '0' }}
        modalContentClass="user-management-modal"
        afterClose={() => {
          formApiRef.current?.reset();
        }}
      >
        <Form
          getFormApi={(api) => {formApiRef.current = api}}
          onSubmit={handleSubmit}
          onSubmitFail={(errors, values) => {
            console.error('表单验证失败:', errors);
            Toast.error('请检查表单输入');
            // 自动滚动到第一个错误字段
            formApiRef.current?.scrollToError();
          }}
          onValueChange={(values, changedValue) => {
            console.log('表单值变化:', changedValue);
            // 可以在这里添加实时验证逻辑
          }}
          validate={validateUserForm}
          layout="vertical"
          labelPosition="top"
          labelAlign="left"
          autoScrollToError={true}
          showValidateIcon={true}
          allowEmpty={false}
          disabled={loading}
          style={{ padding: '20px 0' }}
          initValues={editingUser ? { ...editingUser, password: '' } : { status: 1 }}
        >
          <Form.Section text="基本信息">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Input
                  field="username"
                  label={{ text: '用户名', required: true }}
                  placeholder="请输入用户名"
                  rules={VALIDATION_RULES.username}
                  disabled={!!editingUser}
                  trigger={['blur', 'change']}
                  stopValidateWithError={true}
                  helpText={editingUser ? '编辑时用户名不可修改' : '用户名长度3-20个字符，支持字母、数字、下划线'}
                  name="username"
                  fieldClassName="user-form-username"
                />
              </Col>
              <Col span={12}>
                <Form.Input
                  field="realName"
                  label={{ text: '姓名', required: true }}
                  placeholder="请输入姓名"
                  rules={VALIDATION_RULES.realName}
                  trigger={['blur', 'change']}
                  stopValidateWithError={true}
                  helpText="请输入真实姓名"
                  name="realName"
                  fieldClassName="user-form-realname"
                />
              </Col>
            </Row>
            
            {!editingUser && (
              <Form.Input
                field="password"
                label={{ text: '密码', required: true }}
                type="password"
                placeholder="请输入密码"
                rules={VALIDATION_RULES.password}
                trigger={['blur', 'change']}
                stopValidateWithError={true}
                helpText="密码长度6-20个字符，建议包含字母、数字和特殊字符"
                name="password"
                fieldClassName="user-form-password"
                allowEmptyString={false}
              />
            )}
          </Form.Section>
          
          <Form.Section text="联系方式">
            <Row gutter={16}>
              <Col span={12}>
                <Form.Input
                  field="mobile"
                  label={{ text: '手机号', required: true }}
                  placeholder="请输入手机号"
                  rules={VALIDATION_RULES.mobile}
                  trigger={['blur', 'change']}
                  stopValidateWithError={true}
                  helpText="请输入11位手机号码"
                  name="mobile"
                  fieldClassName="user-form-mobile"
                  transform={(value) => value?.replace(/\s+/g, '')}
                />
              </Col>
              <Col span={12}>
                <Form.Input
                  field="email"
                  label={{ text: '邮箱', required: true }}
                  placeholder="请输入邮箱"
                  rules={VALIDATION_RULES.email}
                  trigger={['blur', 'change']}
                  stopValidateWithError={true}
                  helpText="请输入有效的邮箱地址"
                  name="email"
                  fieldClassName="user-form-email"
                  transform={(value) => value?.toLowerCase().trim()}
                />
              </Col>
            </Row>
          </Form.Section>
          
          <Form.Section text="状态设置">
            <Form.Select
              field="status"
              label={{ text: '状态', required: true }}
              placeholder="请选择状态"
              rules={VALIDATION_RULES.status}
              style={{ width: '200px' }}
              trigger={['change']}
              stopValidateWithError={true}
              helpText="选择用户账户状态"
              name="status"
              fieldClassName="user-form-status"
            >
              <Select.Option value={1}>启用</Select.Option>
              <Select.Option value={0}>禁用</Select.Option>
            </Form.Select>
          </Form.Section>
          
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px', marginTop: '24px' }}>
            <Button 
              onClick={() => {
                // 重置表单
                formApiRef.current?.reset();
                setModalVisible(false);
              }}
              disabled={loading}
            >
              取消
            </Button>
            <Button 
              type="primary" 
              htmlType="submit"
              loading={loading}
              onClick={() => {
                // 手动触发表单验证
                formApiRef.current?.validate()
                  .then((values) => {
                    console.log('表单验证通过:', values);
                  })
                  .catch((errors) => {
                    console.error('表单验证失败:', errors);
                    Toast.error('请检查表单输入');
                  });
              }}
            >
              {editingUser ? '更新' : '创建'}
            </Button>
          </div>
        </Form>
      </Modal>

      {/* 分配角色弹窗 */}
      <Modal
        title="分配角色"
        open={roleModalVisible}
        onCancel={() => setRoleModalVisible(false)}
        footer={null}
        width={400}
        centered
        closable
        closeOnEsc
        maskClosable={false}
        motion
        keepDOM={false}
        size="small"
        bodyStyle={{ padding: '0' }}
        modalContentClass="role-assignment-modal"
        afterClose={() => {
          roleFormApiRef.current?.reset();
          setAssigningUserId(null);
        }}
      >
        <Form
          getFormApi={(api) => {
            roleFormApiRef.current = api;
            console.log('角色分配表单API已获取:', api);
          }}
          onSubmit={handleRoleSubmit}
          onSubmitFail={(errors, values) => {
             console.error('角色分配验证失败:', errors);
             Toast.error('请选择至少一个角色');
             roleFormApiRef.current?.scrollToError();
           }}
           validate={validateRoleForm}
          layout="vertical"
          labelPosition="top"
          labelAlign="left"
          autoScrollToError={true}
          showValidateIcon={true}
          disabled={loading}
          style={{ padding: '20px 0' }}
          initValues={{ roleIds: [] }}
        >
          <Form.Select
            field="roleIds"
            label={{ text: '角色', extra: '可选择多个角色', required: true }}
            placeholder="请选择角色"
            rules={VALIDATION_RULES.roleIds}
            multiple
            style={{ width: '100%' }}
            maxTagCount={3}
            showClear
            filter
            emptyContent="暂无角色数据"
            trigger={['change']}
            stopValidateWithError={true}
            helpText="为用户分配相应的角色权限"
            name="roleIds"
            fieldClassName="role-assignment-select"
            allowEmptyString={false}
          >
            {roles.map((role) => (
              <Select.Option key={role.id} value={role.id}>
                {role.roleName}
              </Select.Option>
            ))}
          </Form.Select>
          
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px', marginTop: '24px' }}>
            <Button 
              onClick={() => {
                roleFormApiRef.current?.reset();
                setRoleModalVisible(false);
              }}
              disabled={loading}
            >
              取消
            </Button>
            <Button 
              type="primary" 
              htmlType="submit"
              loading={loading}
              onClick={() => {
                roleFormApiRef.current?.validate()
                  .then((values) => {
                    console.log('角色分配验证通过:', values);
                  })
                  .catch((errors) => {
                    console.error('角色分配验证失败:', errors);
                    Toast.error('请选择至少一个角色');
                  });
              }}
            >
              确定分配
            </Button>
          </div>
        </Form>
      </Modal>

      {/* 用户角色分配弹窗 */}
      <UserRoleAssignment
        visible={roleAssignmentVisible}
        onCancel={() => {
          setRoleAssignmentVisible(false);
          setSelectedUserId(null);
          setSelectedUserName('');
        }}
        onSuccess={() => {
          setRoleAssignmentVisible(false);
          setSelectedUserId(null);
          setSelectedUserName('');
          loadUsers();
        }}
        userId={selectedUserId!}
        userName={selectedUserName}
      />

      {/* 用户权限分配弹窗 */}
      <PermissionAssignment
        visible={permissionAssignmentVisible}
        onCancel={() => {
          setPermissionAssignmentVisible(false);
          setSelectedUserId(null);
          setSelectedUserName('');
        }}
        onSuccess={() => {
          setPermissionAssignmentVisible(false);
          setSelectedUserId(null);
          setSelectedUserName('');
          loadUsers();
        }}
        targetType="user"
        targetId={selectedUserId!}
        targetName={selectedUserName}
      />

      {/* 用户菜单权限分配弹窗 */}
      <MenuPermissionAssignment
        visible={menuPermissionAssignmentVisible}
        onCancel={() => {
          setMenuPermissionAssignmentVisible(false);
          setSelectedUserId(null);
          setSelectedUserName('');
        }}
        onSuccess={() => {
          setMenuPermissionAssignmentVisible(false);
          setSelectedUserId(null);
          setSelectedUserName('');
          loadUsers();
        }}
        targetType="user"
        targetId={selectedUserId!}
        targetName={selectedUserName}
      />
    </div>
  );
};

export default UserManagement;